package jsyf.oa.service.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.app.DriveDao;
import jsyf.oa.entity.app.DriveEntity;
import jsyf.oa.facade.app.DriveFacade;
import jsyf.oa.ientity.IBaseEntity;

@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class DriveService implements DriveFacade {
    @Autowired
    private DriveDao driveDao;

    @Override
    public String save(String jsonData) {
        DriveEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), DriveEntity.class);
        driveDao.add(entity);
        return entity.getId();
    }

    @Override
    public JSONObject getMonthDistance(String jsonData) {
        JSONObject jsonParam = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParam.getString("userId");
        String date = jsonParam.getString("date");

        List<IBaseEntity> driveList = driveDao.getIBaseEntityByCondition(" AND USER_ID = ? AND CREATE_TIME LIKE ?", new String[]{userId, "%" + date + "%"});
        BigDecimal distance = new BigDecimal("0.0");
        if (driveList != null && driveList.size() > 0) {
            for (int i = 0; i < driveList.size(); i++) {
                BigDecimal b = ((DriveEntity) driveList.get(i)).getDistance();
                distance = distance.add(b);
            }
        }
        JSONObject object = new JSONObject();
        object.put("distance", distance.intValue());
        return object;
    }
}
